﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using QRCoder;
using RapidSalesAdminPortalAPI.DataAccess;
using RapidSalesAdminPortalAPI.Models;
using System.Drawing;
using WebAPI.Common;
using WebAPI.Common.Attributes;
using WebAPI.Controllers;
using WebAPI.Models;
using WebAPI.Util;
using System.Drawing;
using System.IO;
using System;
using System.Data;

namespace RapidSalesAdminPortalAPI.Controllers
{
    //[Authorize]
    [Route("api/[controller]")]
    [ApiController]
    public class FrIpSalesPointController : ParentController
    {
        private readonly RS_AdmPortalContext _db;
        private readonly ILogUtility _logUtility;
        private readonly ILogger _logger;
        private readonly IDataProtectorUtility _dataProtectorUntility;
        private readonly IConfiguration _configuration;

        public FrIpSalesPointController(RS_AdmPortalContext db, IConfiguration configuration, ILogUtility logUtility, ILogger<FrIpSalesPointController> logger, IDataProtectorUtility dataProtectorUntility)
        {
            _db = db;
            _logUtility = logUtility; // sample code for DI of common utility class
            _logger = logger;
            _configuration = configuration;
            _dataProtectorUntility = dataProtectorUntility;
        }

        [HttpPost("GetSalesPointList")]
        public async Task<ActionResult<ResultMsg>> GetSalesPointList([FromBody] GetSalesPointListRequest requestModel)
        {
            var resultMsg = new ResultMsg();
            try
            {
                IQueryable<FrIpSalesPoint> paComont = _db.FrIpSalesPoints.Include(x => x.OperationArea).Where(x => x.IsDelete == false)
                    .AsQueryable();
                if (!string.IsNullOrWhiteSpace(requestModel.Enable))
                    paComont = paComont.Where(x => x.Enable.ToString() == requestModel.Enable);
                if (!string.IsNullOrWhiteSpace(requestModel.Code))
                    paComont = paComont.Where(x => x.Code.Contains(requestModel.Code));
                if (!string.IsNullOrWhiteSpace(requestModel.Name))
                    paComont = paComont.Where(x => x.NameEn.Contains(requestModel.Name));
                if (!string.IsNullOrWhiteSpace(requestModel.Description))
                    paComont = paComont.Where(x => x.DescriptionEn.Contains(requestModel.Description));
                if (!string.IsNullOrWhiteSpace(requestModel.OperationArea))
                    paComont = paComont.Where(x => x.OperationArea.Value.Contains(requestModel.OperationArea));

                var paData = paComont.ToList().Select(x => new GetSalesPointListResponse()
                {
                    Id = x.Id,
                    Code = x.Code,
                    NameEn = x.NameEn,
                    DescriptionEn = x.DescriptionEn,
                    NameSc = x.NameSc,
                    DescriptionSc = x.DescriptionSc,
                    NameTc = x.NameTc,
                    DescriptionTc = x.DescriptionTc,
                    OperationArea = x.OperationArea.Value,
                    Passcode = x.Passcode,
                    Exclusive = x.Exclusive.GetValueOrDefault(),
                    OperationAreaId = x.OperationAreaId,
                    QrCodeUrl = x.QrCodeUrl,
                    Enable = x.Enable,
                    CreateDate = x.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                    UpdateDate = x.UpdateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                    CreateUser = UserNameQuery(x.CreateUser),
                    UpdateUser = UserNameQuery(x.UpdateUser)
                }).AsQueryable();

                if (!string.IsNullOrWhiteSpace(requestModel.Field) && paComont.Count() > 0)
                    paData = DBHelper.DataSorting(paData, requestModel.Field, requestModel.Order);
                else
                    paData = DBHelper.DataSorting(paData, "CreateDate", "desc");

                var SalesPoint = await BasePageOutputExtensions.ToPagedListAsync(paData.ToList(), requestModel.Page, requestModel.PageSize);

                return resultMsg.SetResultMsg(
                     (int)ResultCode.Success,
                     HelperUtility.GetDescription(ResultCode.Success),
                     SalesPoint);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                return resultMsg.SetResultMsg(
                     (int)ResultCode.ErrorOnRequestUnMarshalling,
                     HelperUtility.GetDescription(ResultCode.ErrorOnRequestUnMarshalling),
                     null);
            }
        }

        [HttpGet("{id}")]
        public async Task<ActionResult<ResultMsg>> GetSalesPoint(Guid id)
        {
            var resultMsg = new ResultMsg();
            try
            {
                FrIpSalesPoint pa = await _db.FrIpSalesPoints.Include(x => x.OperationArea).FirstOrDefaultAsync(x => x.Id == id);
                var productEventList = await _db.FrIpSalesPointProducts.Include(x => x.ProductEvenet).Select
                    (x => new ProductEventInfo()
                    {
                        ProductEventId = x.ProductEvenetId,
                        CutOffTime = x.CutOffTime,
                        ProductName = x.ProductEvenet.Product.ProductNameEn,
                        EventName = x.ProductEvenet.Event.EventNameEn
                    }).ToListAsync();
                if (pa == null)
                {
                    return resultMsg.SetResultMsg(
                         (int)ResultCode.UserNotFound,
                         HelperUtility.GetDescription(ResultCode.UserNotFound),
                         null);
                }

                var SalesPoint = new GetSalesPointListResponse()
                {
                    Id = pa.Id,
                    Code = pa.Code,
                    NameEn = pa.NameEn,
                    NameSc = pa.NameSc,
                    NameTc = pa.NameTc,
                    DescriptionEn = pa.DescriptionEn,
                    DescriptionSc = pa.DescriptionSc,
                    DescriptionTc = pa.DescriptionTc,
                    OperationArea = pa.OperationArea.Value,
                    OperationAreaId = pa.OperationAreaId,
                    ProductEventList = productEventList,
                    Passcode = pa.Passcode,
                    Exclusive = pa.Exclusive.GetValueOrDefault(),
                    QrCodeUrl = pa.QrCodeUrl,
                    //ProductEventIds = productEvenetIds,
                    HasProduct = productEventList.Count() > 0 ? true : false,
                    Enable = pa.Enable,
                    CreateDate = pa.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                    UpdateDate = pa.UpdateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                    CreateUser = UserNameQuery(pa.CreateUser),
                    UpdateUser = UserNameQuery(pa.UpdateUser)
                };
                return resultMsg.SetResultMsg(
                     (int)ResultCode.Success,
                     HelperUtility.GetDescription(ResultCode.Success),
                     SalesPoint);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                return resultMsg.SetResultMsg(
                     (int)ResultCode.ErrorOnRequestUnMarshalling,
                     HelperUtility.GetDescription(ResultCode.ErrorOnRequestUnMarshalling),
                     null);
            }
        }


        [HttpPost("GetProductEventList")]
        public async Task<ActionResult<ResultMsg>> GetProductEventList(GetProductEventListRequest requestModel)
        {
            var resultMsg = new ResultMsg();
            try
            {
                var resonse = new GetProductEventListResponse();

                var pa = _db.FrIpProductEvents.Include(x => x.Product).Include(x => x.Event).AsQueryable();
                if (!string.IsNullOrWhiteSpace(requestModel.ProductField))
                {
                    resonse.ProductFieldList = pa.Where(x =>
                       x.Product.ProductCode.Contains(requestModel.ProductField)
                    || x.Product.ProductNameEn.Contains(requestModel.ProductField)
                    || x.Product.ProductNameSc.Contains(requestModel.ProductField)
                    || x.Product.ProductNameTc.Contains(requestModel.ProductField)
                    ).Select(x => x.Product.ProductNameEn).Distinct().ToList();
                }
                else
                {
                    resonse.ProductFieldList = pa.Where(x => !string.IsNullOrWhiteSpace(x.Product.ProductNameEn)).Select(x => x.Product.ProductNameEn).Distinct().ToList();
                }


                if (!string.IsNullOrWhiteSpace(requestModel.EventField))
                {
                    resonse.EventFieldList = pa.Where(x =>
                    x.Event.EventCode.Contains(requestModel.EventField) ||
                    x.Event.EventNameEn.Contains(requestModel.EventField)
                    || x.Event.EventNameSc.Contains(requestModel.EventField)
                    || x.Event.EventNameTc.Contains(requestModel.EventField)
                    ).Select(x => x.Event.EventNameEn).Distinct().ToList();
                }
                else {
                    resonse.EventFieldList = pa.Where(x=> !string.IsNullOrWhiteSpace(x.Event.EventNameEn)).Select(x => x.Event.EventNameEn).Distinct().ToList();
                }

                return resultMsg.SetResultMsg(
                     (int)ResultCode.Success,
                     HelperUtility.GetDescription(ResultCode.Success),
                     resonse);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                return resultMsg.SetResultMsg(
                     (int)ResultCode.ErrorOnRequestUnMarshalling,
                     HelperUtility.GetDescription(ResultCode.ErrorOnRequestUnMarshalling),
                     null);
            }
        }
            
        [HttpPost("GetSalesPointProductBySalePointId")]
        public async Task<ActionResult<ResultMsg>> GetSalesPointProductBySalePointId([FromBody] GetSalesPointProductRequest requestModel)
        {
            var resultMsg = new ResultMsg();
            try
            {
                var oldList = await _db.FrIpSalesPointProducts.Where(x => x.SalesPointId == x.SalesPointId).ToListAsync();
                var oldIdList = oldList.Select(x => x.ProductEvenetId).ToList();

                var pa = _db.FrIpProductEvents.Include(x => x.Product).Include(x => x.Event).AsQueryable();
                if (pa == null)
                {
                    return resultMsg.SetResultMsg(
                         (int)ResultCode.NoDataFound,
                         HelperUtility.GetDescription(ResultCode.NoDataFound),
                         null);
                }

                if (!string.IsNullOrWhiteSpace(requestModel.ProductField))
                {
                    pa = pa.Where(x =>
                       x.Product.ProductCode.Contains(requestModel.ProductField)
                    || x.Product.ProductNameEn.Contains(requestModel.ProductField)
                    || x.Product.ProductNameSc.Contains(requestModel.ProductField)
                    || x.Product.ProductNameTc.Contains(requestModel.ProductField)
                    );
                }

                if (!string.IsNullOrWhiteSpace(requestModel.EventField))
                {
                    pa = pa.Where(x =>
                       x.Event.EventAk.Contains(requestModel.EventField)
                    || x.Event.EventNameEn.Contains(requestModel.EventField)
                    || x.Event.EventNameTc.Contains(requestModel.EventField)
                    || x.Event.EventNameSc.Contains(requestModel.EventField)
                    );
                }

                var products = await pa.Select(x => new ProductEventInfo()
                {
                    ProductEventId = x.Id,
                    CutOffTime = 0,
                    ProductName = x.Product.ProductNameEn,
                    EventName = x.Event.EventNameEn
                }).ToListAsync();

                foreach (var pro in products)
                {
                    if (oldIdList.Contains(pro.ProductEventId))
                    {
                        pro.IsExist = true;
                        pro.CutOffTime = oldList.FirstOrDefault(x => x.ProductEvenetId == pro.ProductEventId).CutOffTime;
                    }
                    else
                    {
                        pro.IsExist = false;
                        pro.CutOffTime = 0;
                    }
                }

                //var products = await _db.FrIpSalesPointProducts
                //    .Join(_db.FrIpDataDictionaries,
                //    a=>a.ProductId,
                //    b=>b.Id,
                //    (a, b)=> new { a, b })
                //    .Where(x => x.a.SalesPointId == SalesPointId)
                //    .Select(x => new GetSalesPointProductListResponse
                //    { 
                //        ProductId = x.a.ProductId,
                //        Function = x.b.CodeItemName,
                //        ProductCode = x.b.DefaultSetValue,
                //        ProductName = x.b.Description,
                //        IsCheck = true
                //    }).ToListAsync();

                return resultMsg.SetResultMsg(
                     (int)ResultCode.Success,
                     HelperUtility.GetDescription(ResultCode.Success),
                     products.OrderByDescending(x=>x.IsExist));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                return resultMsg.SetResultMsg(
                     (int)ResultCode.ErrorOnRequestUnMarshalling,
                     HelperUtility.GetDescription(ResultCode.ErrorOnRequestUnMarshalling),
                     null);
            }
        }

        [HttpPost("SalesPointByProductId")]
        public async Task<ActionResult<ResultMsg>> SalesPointByProductId([FromBody] SalesPointByProductIdRequest requestModel)
        {
            var resultMsg = new ResultMsg();
            try
            {
                var pa = _db.FrIpSalesPointProducts.Include(x => x.SalesPoint).Where(x => x.ProductEvenet.ProductId == requestModel.ProductId).AsQueryable();
                if (pa == null)
                {
                    return resultMsg.SetResultMsg(
                         (int)ResultCode.NoDataFound,
                         HelperUtility.GetDescription(ResultCode.NoDataFound),
                         null);
                }

                if (!string.IsNullOrWhiteSpace(requestModel.Code))
                {
                    pa = pa.Where(x => x.SalesPoint.Code.Contains(requestModel.Code));
                }

                if (!string.IsNullOrWhiteSpace(requestModel.Name))
                {
                    pa = pa.Where(x => x.SalesPoint.NameEn.Contains(requestModel.Name));
                }

                var salePoints = await pa
                    .Select(x => new GetSalesPointListResponse
                    {
                        Code = x.SalesPoint.Code,
                        NameEn = x.SalesPoint.NameEn,
                        NameTc = x.SalesPoint.NameTc,
                        NameSc = x.SalesPoint.NameSc,
                    })
                    .OrderBy(x => x.Code).ToListAsync();

                return resultMsg.SetResultMsg(
                     (int)ResultCode.Success,
                     HelperUtility.GetDescription(ResultCode.Success),
                     salePoints);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                return resultMsg.SetResultMsg(
                     (int)ResultCode.ErrorOnRequestUnMarshalling,
                     HelperUtility.GetDescription(ResultCode.ErrorOnRequestUnMarshalling),
                     null);
            }
        }


        [Log("SalesPoint", "UpdateSalesPoint", description: "SalesPoint/UpdateSalesPoint", LogType: Enums.LogType.SalePointLog)]
        [HttpPut("UpdateSalesPoint")]
        public async Task<ActionResult<ResultMsg>> UpdateSalesPoint([FromBody] UpdateSalesPointRequest SalesPoint)
        {
            var resultMsg = new ResultMsg();
            try
            {
                if (!SalesPointExists(SalesPoint.ID))
                {
                    return resultMsg.SetResultMsg(
                     (int)ResultCode.UserNotFound,
                     HelperUtility.GetDescription(ResultCode.UserNotFound),
                     null);
                }

                var oldProductEventList = await _db.FrIpSalesPointProducts.Include(x => x.ProductEvenet)
                    .Where(x => x.SalesPointId == SalesPoint.ID && x.ProductEvenetId != null && x.ProductEvenetId != Guid.Empty
                    ).Select(x => x.ProductEvenet.Id).ToListAsync();

                if (SalesPoint.ProductEventList != null && SalesPoint.ProductEventList.Count > 0)
                {
                    var ProductEventIds = SalesPoint.ProductEventList.Select(x => x.ProductEventId).ToList();

                    var addList = ProductEventIds.Except(oldProductEventList).ToList();
                    var updateIdList = oldProductEventList.Intersect(ProductEventIds).ToList();
                    var delList = oldProductEventList.Except(ProductEventIds).ToList();
                    var updateList = await _db.FrIpSalesPointProducts.Where(x => updateIdList.Contains(x.ProductEvenetId)).ToListAsync();

                    var addResult = new List<FrIpSalesPointProduct>();
                    var delResult = _db.FrIpSalesPointProducts.Include(x => x.ProductEvenet).Where(x => delList.Contains(x.ProductEvenet.Id)).ToList();

                    //addList
                    if (addList != null && addList.Count > 0)
                    {
                        foreach (var productEventId in addList)
                        {
                            var info = SalesPoint.ProductEventList.FirstOrDefault(x => x.ProductEventId == productEventId);
                            addResult.Add(new FrIpSalesPointProduct()
                            {
                                Id = Guid.NewGuid(),
                                ProductEvenetId = productEventId,
                                SalesPointId = SalesPoint.ID,
                                CutOffTime = info.CutOffTime,
                                RapidSalesStartDate = DateTime.Now,
                                RapidSalesEndDate = DateTime.Now,
                                RapidSalesThumbnailUrl = ""
                            });
                        }
                        await _db.FrIpSalesPointProducts.AddRangeAsync(addResult);
                    }

                    //UpdateList
                    if (updateList != null && updateList.Count > 0)
                    {
                        foreach (var uptInfo in updateList)
                        {
                            var info = SalesPoint.ProductEventList.FirstOrDefault(x => x.ProductEventId == uptInfo.ProductEvenetId);
                            uptInfo.CutOffTime = info.CutOffTime;
                        }
                        _db.FrIpSalesPointProducts.UpdateRange(updateList);
                    }
                    _db.FrIpSalesPointProducts.RemoveRange(delResult);

                }


                FrIpSalesPoint dt = await _db.FrIpSalesPoints.FirstOrDefaultAsync(x => x.Id == SalesPoint.ID);
                dt.Code = SalesPoint.Code;
                dt.NameEn = SalesPoint.NameEn;
                dt.NameTc = SalesPoint.NameTc;
                dt.NameSc = SalesPoint.NameSc;
                dt.DescriptionEn = SalesPoint.DescriptionEn;
                dt.DescriptionTc = SalesPoint.DescriptionTc;
                dt.DescriptionSc = SalesPoint.DescriptionSc;
                dt.OperationAreaId = SalesPoint.OperationAreaId;
                dt.Passcode = SalesPoint.Passcode;  
                dt.Exclusive = SalesPoint.Exclusive;
                dt.Enable = SalesPoint.Enable;
                dt.UpdateUser = CurrentUserId;
                dt.UpdateDate = DateTime.Now;
                _db.Entry(dt).State = EntityState.Modified;

                await _db.SaveChangesAsync();
                return resultMsg.SetResultMsg(
                  (int)ResultCode.Success,
                  HelperUtility.GetDescription(ResultCode.Success),
                  null);
            }
            catch (Exception ex)
            {
                _logger.LogError("SalesPoint/UpdateSalesPoint Error:" + ex.Message);
                return resultMsg.SetResultMsg(
                 (int)ResultCode.ErrorOnRequestUnMarshalling,
                 HelperUtility.GetDescription(ResultCode.ErrorOnRequestUnMarshalling),
                 null);
            }
        }


        [Log("SalesPoint", "AddSalesPoint", description: "SalesPoint/AddSalesPoint", LogType: Enums.LogType.SalePointLog)]
        [HttpPost("AddSalesPoint")]
        public async Task<ActionResult<ResultMsg>> AddSalesPoint([FromBody] AddSalesPointRequest SalesPoint)
        {
            var resultMsg = new ResultMsg();
            try
            {

                if (SalesPointExists(SalesPoint.Code))
                {
                    return resultMsg.SetResultMsg(
                     (int)ResultCode.DataAlreadyExists,
                     HelperUtility.GetDescription(ResultCode.DataAlreadyExists),
                     null);
                }
                var addList = new List<FrIpSalesPointProduct>();
                DateTime NowTime = DateTime.Now;
                Guid Id = Guid.NewGuid();
                FrIpSalesPoint dt = new FrIpSalesPoint()
                {
                    Id = Id,
                    Code = SalesPoint.Code,
                    NameEn = SalesPoint.NameEn,
                    NameTc = SalesPoint.NameTc,
                    NameSc = SalesPoint.NameSc,
                    DescriptionEn = SalesPoint.DescriptionEn,
                    DescriptionTc = SalesPoint.DescriptionTc,
                    DescriptionSc = SalesPoint.DescriptionSc,
                    OperationAreaId = SalesPoint.OperationAreaId,
                    Enable = SalesPoint.Enable,
                    Passcode = SalesPoint.Passcode,
                    QrCodeUrl = _configuration["SalesPortal:DirectUrlHost"].ToString(),
                    Exclusive = SalesPoint.Exclusive,
                    CreateUser = CurrentUserId,
                    UpdateUser = CurrentUserId,
                    CreateDate = NowTime,
                    UpdateDate = NowTime
                };
                var model = await _db.FrIpSalesPoints.AddAsync(dt);

                if (SalesPoint.ProductEventIds != null && SalesPoint.ProductEventIds.Count > 0)
                {
                    foreach (var productEventId in SalesPoint.ProductEventIds)
                    {
                        addList.Add(new FrIpSalesPointProduct()
                        {
                            Id = Guid.NewGuid(),
                            SalesPointId = Id,
                            ProductEvenetId = productEventId,
                            RapidSalesRemarksSc = SalesPoint.RapidSalesRemarksChi,
                            RapidSalesRemarksTc = SalesPoint.RapidSalesRemarksTc,
                            RapidSalesRemarksEng = SalesPoint.RapidSalesRemarksEng,
                            RapidSalesThumbnailUrl = SalesPoint.RapidSalesThumbnailUrl,
                            RapidSalesStartDate = SalesPoint.RapidSalesStartDate,
                            RapidSalesEndDate = SalesPoint.RapidSalesEndDate,
                            ParentalGuidance = SalesPoint.ParentalGuidance
                        });
                    }

                    await _db.FrIpSalesPointProducts.AddRangeAsync(addList);
                }

                await _db.SaveChangesAsync();
                return resultMsg.SetResultMsg(
                 (int)ResultCode.Success,
                 HelperUtility.GetDescription(ResultCode.Success),
                 Id);
            }
            catch (Exception ex)
            {
                _logger.LogError("SalesPoint/AddSalesPoint Error:" + ex.Message);
                return resultMsg.SetResultMsg(
                 (int)ResultCode.ErrorOnRequestUnMarshalling,
                 HelperUtility.GetDescription(ResultCode.ErrorOnRequestUnMarshalling),
                 null);
            }
        }


        [Log("SalesPoint", "DeleteSalesPoint", description: "SalesPoint/DeleteSalesPoint", LogType: Enums.LogType.SalePointLog)]
        [HttpDelete("DeleteSalesPoint")]
        public async Task<ActionResult<ResultMsg>> DeleteSalesPoint([FromBody] EnableSalesPointRequest SalesPoint)
        {
            ResultMsg resultMsg = new();
            List<FrIpSalesPoint> paDt = await _db.FrIpSalesPoints?.Where(x => SalesPoint.Ids.Contains(x.Id.ToString()))?.ToListAsync();
            if (paDt == null || paDt.Count < 1)
            {
                return resultMsg.SetResultMsg(
                 (int)ResultCode.NoDataFound,
                 HelperUtility.GetDescription(ResultCode.NoDataFound),
                 null);
            }
            DateTime nowTime = DateTime.Now;
            for (int i = 0; i < paDt.Count; i++)
            {
                paDt[i].IsDelete = true;
                paDt[i].UpdateDate = nowTime;
                paDt[i].UpdateUser = CurrentUserId;
            }
            await _db.SaveChangesAsync();
            return resultMsg.SetResultMsg(
                (int)ResultCode.Success,
                HelperUtility.GetDescription(ResultCode.Success),
                null);
        }


        [Log("SalesPoint", "EnableSalesPoint", description: "SalesPoint/EnableSalesPoint", LogType: Enums.LogType.SalePointLog)]
        [HttpPut("EnableSalesPoint")]
        public async Task<ActionResult<ResultMsg>> EnableSalesPoint([FromBody] EnableSalesPointRequest requestModel)
        {
            ResultMsg resultMsg = new();
            var accountList = _db.FrIpSalesPoints.Where(x => requestModel.Ids.Contains(x.Id.ToString())).ToList();
            if (accountList == null || accountList.Count <= 0)
            {
                return resultMsg.SetResultMsg(
               (int)ResultCode.NoDataFound,
               HelperUtility.GetDescription(ResultCode.NoDataFound),
               null);
            }
            foreach (var account in accountList)
            {
                account.Enable = requestModel.Enable;
            }

            await _db.SaveChangesAsync();
            return resultMsg.SetResultMsg(
                (int)ResultCode.Success,
                HelperUtility.GetDescription(ResultCode.Success),
                null);
        }

        //[NonAction]
        //public void GenerateQRCode(string text, string filePath)
        //{
        //    QRCodeGenerator qrGenerator = new QRCodeGenerator();
        //    QRCodeData qrCodeData = qrGenerator.CreateQrCode(text, QRCodeGenerator.ECCLevel.Q);
        //    QRCode qrCode = new QRCode(qrCodeData);
        //    Bitmap qrImage = qrCode.GetGraphic(20, Color.Black, Color.White, true);

        //    string directory = "path/to/your/folder"; // 指定文件夹路径
        //    if (!Directory.Exists(directory))
        //    {
        //        Directory.CreateDirectory(directory);
        //    }

        //    string fullPath = Path.Combine(directory, "qrcode.png");
        //    qrImage.Save(fullPath);
        //}

        [NonAction]
        private bool SalesPointExists(Guid id)
        {
            return _db.FrIpSalesPoints.Any(e => e.Id == id);
        }

        [NonAction]
        private bool SalesPointExists(string Code)
        {
            return _db.FrIpSalesPoints.Any(e => e.Code == Code);
        }

        [NonAction]
        public string UserNameQuery(Guid id)
        {
            FrIpAdministratorAccount dt = _db.FrIpAdministratorAccounts?.FirstOrDefault(x => x.Id.Equals(id));
            return dt?.AccountName ?? "";
        }
    }
}
